import "./qrcode.less";
import "@/static/font/iconfont.css";

import { useId, useRef } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { Snapshot, Text, View } from "@tarojs/components";
import { useBoolean, useUpdateEffect } from "ahooks";

import ByText from "@/components/ui/ByText";
import ByIcon from "@/components/ui/ByIcon";
import Page from "@/components/common/Page";
import ByButton from "@/components/ui/ByButton";
import ByQrcode from "@/components/ui/ByQrcode";
import PageHeader from "@/components/common/PageHeader";

import { ACCESSTOKEN } from "@/utils/constant";
import useFetch from "@/hooks/useFetch";
import ApiFinance from "@/api/finance";
import setting from "@/utils/setting";

export default () => {
  const token = Taro.getStorageSync(ACCESSTOKEN);

  const { params } = useRouter();
  const receiptBillId = Number(params.receiptBillId);
  const query = { receiptBillId };

  // false 直接扫码支付｜true 会跳转到红杉树H5页面
  const [isH5, { toggle }] = useBoolean(true);

  const nodeId = useRef(`snapshot_` + useId());

  const { data: payData, run } = useFetch<{
    payUrl: string;
  }>(ApiFinance.createPay, "POST", { manual: true });

  const { data } = useFetch(ApiFinance.receiptDetail, {
    defaultParams: [query],
    onAfter: (res: any) => res.receiptBill,
  });

  // 获取截图图片
  const generagePic = (): Promise<string> => {
    return new Promise((resolve, reject) => {
      Taro.createSelectorQuery()
        .select("#" + nodeId.current)
        .node()
        .exec((res) => {
          const node = res[0].node;
          node.takeSnapshot({
            type: "file",
            format: "png",
            success: (res) => {
              resolve(res.tempFilePath);
            },
            fail(err) {
              reject(err);
            },
          });
        });
    });
  };

  // 保存至相册
  const saveToAlbum = async () => {
    const filePath = await generagePic();

    Taro.saveImageToPhotosAlbum({
      filePath,
      success() {
        Taro.showToast({ title: "保存成功" });
      },
      async fail(err: any) {
        // 授权拒绝
        if (err.errno == 103) {
          const { confirm } = await Taro.showModal({
            title: "保存失败",
            content: "需要授权“添加到相册”",
            confirmText: "去设置",
          });

          if (confirm) {
            Taro.openSetting({});
          }
        } else {
          Taro.showToast({ icon: "none", title: "保存失败" });
        }
      },
    });
  };

  useUpdateEffect(() => {
    if (!isH5 && !payData) {
      run(query);
    }
  }, [isH5]);

  const qrcodeURL = data
    ? isH5
      ? setting.webUrl +
        `/order/detail/${data.receiptBillId}?intentCustomerId=${data.intentCustomerId}&token=${token}`
      : payData?.payUrl
    : "";

  return (
    <Page skyline slotHeader={<PageHeader />} footerStyle={false}>
      <View className="m-3 bg-white rounded-md">
        <Snapshot mode="view" id={nodeId.current} className="text-center">
          <View className="p-4 bg-white rounded-md">
            <View className="mb-4">{data?.orgName}</View>
            <View className="mb-3 text-sm text-second">{data?.summary}</View>
            <View className="flex-center relative w-[500px] mx-auto">
              <ByQrcode text={qrcodeURL} width={500} />

              {!qrcodeURL && (
                <View className="flex-center absolute top-0 left-0 w-full h-full bg-page rounded-md">
                  <ByText type="third">二维码生成失败</ByText>
                </View>
              )}
            </View>
            <ByText type="third" size="xs" className="mt-3">
              {isH5 ? "使用手机扫码查看" : "使用微信或支付宝扫码支付"}
            </ByText>
          </View>
        </Snapshot>

        <ByButton
          size="large"
          type="success"
          className="my-3 w-1/2"
          onClick={saveToAlbum}
        >
          保存至相册
        </ByButton>

        <View className="flex-center my-3">
          <View className="flex-center text-sm text-second" onClick={toggle}>
            <ByIcon name="Switch2" className="text-success" />
            <Text>切换为“{isH5 ? "直接扫码支付" : "红杉树支付H5"}”</Text>
          </View>
        </View>

        <View className="safe-footer" />
      </View>
    </Page>
  );
};
